import hashlib
import os

from SCons.Script import Default

Import("env", "projenv")


def BuildSharedLibrary(env, variant_dir, src_dir, src_filter=None):
    """
    Args:
        env:
        variant_dir:
        src_dir:
        src_filter:
    """
    env.ProcessUnFlags(env.get("BUILD_UNFLAGS"))
    return env.SharedLibrary(env.subst(variant_dir), src_dir)


if env['PIOPLATFORM'] in ['windows_x86']:
    # env.ProcessProgramDeps()
    # env.ProcessProjectDeps()
    # env.Replace(CCFLAGS=['-shared'])
    if env['LINKFLAGS'].__contains__('-static'):
        env['LINKFLAGS'].remove('-static')
    # if env['LINKFLAGS'].__contains__('-static-libgcc'):
    #     env['LINKFLAGS'].remove('-static-libgcc')
    # if env['LINKFLAGS'].__contains__('-static-libstdc++'):
    #     env['LINKFLAGS'].remove('-static-libstdc++')
    if projenv['LINKFLAGS'].__contains__('-static'):
        projenv['LINKFLAGS'].remove('-static')
    # if projenv['LINKFLAGS'].__contains__('-static-libgcc'):
    #     projenv['LINKFLAGS'].remove('-static-libgcc')
    # if projenv['LINKFLAGS'].__contains__('-static-libstdc++'):
    #     projenv['LINKFLAGS'].remove('-static-libstdc++')
    env['LINKFLAGS'] += ['-shared', ]
    env.Append(
        _LIBFLAGS=" -luser32 -lkernel32 -lstdc++ -lgcc -lm -lgcc")
    env.AddMethod(BuildSharedLibrary)
    target_bin = env.BuildSharedLibrary(os.path.join("$BUILD_DIR", env.subst("$PROGNAME")), env["PIOBUILDFILES"])
    env['BUILDERS']['Program'] = None
    projenv['BUILDERS']['Program'] = None
    env['STATIC_AND_SHARED_OBJECTS_ARE_THE_SAME'] = 1
    projenv['STATIC_AND_SHARED_OBJECTS_ARE_THE_SAME'] = 1
    Default([target_bin])
elif env['PIOPLATFORM'] in ['sylixos_arm', 'sylixos_x86', 'sylixos_loong2k', 'sylixos_loongson']:
    # env.ProcessProgramDeps()
    # env.ProcessProjectDeps()
    # env.Replace(CCFLAGS=['-shared'])
    if env['LINKFLAGS'].__contains__('-static'):
        env['LINKFLAGS'].remove('-static')
    # if env['LINKFLAGS'].__contains__('-static-libgcc'):
    #     env['LINKFLAGS'].remove('-static-libgcc')
    # if env['LINKFLAGS'].__contains__('-static-libstdc++'):
    #     env['LINKFLAGS'].remove('-static-libstdc++')
    if projenv['LINKFLAGS'].__contains__('-static'):
        projenv['LINKFLAGS'].remove('-static')
    # if projenv['LINKFLAGS'].__contains__('-static-libgcc'):
    #     projenv['LINKFLAGS'].remove('-static-libgcc')
    # if projenv['LINKFLAGS'].__contains__('-static-libstdc++'):
    #     projenv['LINKFLAGS'].remove('-static-libstdc++')
    env['LINKFLAGS'] += ['-shared', '-fPIC', '-nostartfiles', '-nostdlib', "--specs=nosys.specs", '-static-libgcc',
                         '-static-libstdc++']
    projenv['LINKFLAGS'] += ['-shared', '-fPIC', '-nostartfiles', '-nostdlib', "--specs=nosys.specs", '-static-libgcc',
                             '-static-libstdc++']
    env.Append(
        _LIBFLAGS=" -lstdc++ -lgcc -lm -lgcc ")
    projenv.Append(
        _LIBFLAGS=" -lstdc++ -lgcc -lm -lgcc ")

    env.AddMethod(BuildSharedLibrary)
    target_bin = env.BuildSharedLibrary(os.path.join("$BUILD_DIR", env.subst("$PROGNAME")), env["PIOBUILDFILES"])
    env['BUILDERS']['Program'] = None
    projenv['BUILDERS']['Program'] = None
    env['STATIC_AND_SHARED_OBJECTS_ARE_THE_SAME'] = 1
    projenv['STATIC_AND_SHARED_OBJECTS_ARE_THE_SAME'] = 1
    Default([target_bin])
else:
    env.Replace(LINKFLAGS=[i for i in env['LINKFLAGS'] if i not in ['-nostartfiles', '-nostdlib']])
    env.Append(LINKFLAGS=["--specs=nosys.specs"])


# access to global construction environment
# print env

# access to project construction environment
# print projenv

# Dump construction environments (for debug purpose)
# print(env.Dump())
# print(projenv.Dump())


# def before_buildprog(source, target, env):
#     print("before_buildprog")
#     print(os.getcwd())
# if os.path.exists('web'):
#     os.system("makefsdata.exe web")

# env.Append(ldscript='stm32f103ve.ld')


def before_upload(source, target, env):
    """
    Args:
        source:
        target:
        env:
    """
    print("before_upload")
    # do some actions


def after_upload(source, target, env):
    """
    Args:
        source:
        target:
        env:
    """
    print("after_upload")
    # do some actions


def buildMD5(source, target, env):
    """
    Args:
        source:
        target:
        env:
    """
    print("buildMD5")
    f = str(target[0])
    print(f, type(f))
    fh = open(f, "rb")
    fr = fh.read()
    md5key = hashlib.md5(fr).hexdigest()

    # Store new PLC filename based on md5 key
    f = open("lastbuildPLC.md5", "w")
    f.write(md5key)
    f.close()


env.AddPreAction("upload", before_upload)
env.AddPostAction("upload", after_upload)
# env.AddPreAction("buildprog", before_buildprog)
# env.AddPostAction("$BUILD_DIR/firmware.bin", buildMD5)
# env.AddPostAction("$BUILD_DIR/program.dll", buildMD5)
